package ve.com.wayoyo.wuml_case.Bluetooth;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

public class ConnectThread extends Thread {
	private final BluetoothSocket mmSocket;
	private final BluetoothDevice mmDevice;
	private BluetoothAdapter mBluetoothAdapter;
	private String _diagrama;

	public ConnectThread(BluetoothDevice device, String diagrama) {
		// Use a temporary object that is later assigned to mmSocket,
		// because mmSocket is final
		BluetoothSocket tmp = null;
		mmDevice = device;
		this._diagrama = diagrama;
		// Get a BluetoothSocket to connect with the given BluetoothDevice
		try {
			// MY_UUID is the app's UUID string, also used by the server code
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			UUID mY_UUIDUuid = UUID
					.fromString("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
			tmp = device.createRfcommSocketToServiceRecord(mY_UUIDUuid);
		} catch (IOException e) {
		}
		mmSocket = tmp;
	}

	public void run() {
		// Cancel discovery because it will slow down the connection
		mBluetoothAdapter.cancelDiscovery();

		try {
			// Connect the device through the socket. This will block
			// until it succeeds or throws an exception
			mmSocket.connect();
		} catch (IOException connectException) {
			// Unable to connect; close the socket and get out
			try {
				mmSocket.close();
			} catch (IOException closeException) {
			}
			return;
		}

		// Do work to manage the connection (in a separate thread)
		manageConnectedSocket(mmSocket);
	}

	private void manageConnectedSocket(BluetoothSocket mmSocket2) {
		InputStream tmpIn = null;
		OutputStream tmpOut = null;
		// Get the input and output streams, using temp objects because
		// member streams are final
		try {
			tmpIn = mmSocket2.getInputStream();
			tmpOut = mmSocket2.getOutputStream();
			String[] lines = _diagrama.split("\n");
			byte[] bufferIn = new byte[1024];
			Boolean flagEnviar = true;
			int i = 1;
			while (true) {
				if (flagEnviar) {
					if (i < lines.length) {
						byte[] bufferOut = (lines[i] + "\n").getBytes();
						i++;
						tmpOut.flush();
						tmpOut.write(bufferOut);
						flagEnviar = false;
					} else {
						byte[] bufferOut = "EOF".getBytes();
						tmpOut.write(bufferOut);
						break;
					}
				} else {
					int bytes = tmpIn.read(bufferIn);
					String aux = new String(bufferIn);
					if (aux.contains("Ok")) {
						flagEnviar = true;
					}
				}
			}

		} catch (IOException e) {
		}

	}

	/** Will cancel an in-progress connection, and close the socket */
	public void cancel() {
		try {
			mmSocket.close();
		} catch (IOException e) {
		}
	}
}